#pragma once
#include <iostream>
#include <string>
#include "Inetaddr.hpp"
#include <vector>
#include "log.hpp"

using namespace LogModule;
class Route
{
private:
    std::vector<Inetaddr> _online_user;
    bool Isexist(Inetaddr &peer)
    {
        for (auto &user : _online_user)
            if (user == peer)
                return true;
        return false;
    }

public:
    Route()
    {
    }
    void messRoute(int sockfd, const std::string &mess, Inetaddr &peer)
    {
        if (!Isexist(peer))
        {
            LOG(Loglevel::INFO) << "add a user. IP:" << peer.ip() << " " << "port:" << peer.port();
            _online_user.push_back(peer);
        }
        std::string sen_mess = "IP:" + peer.ip() + " port:" + std::to_string(peer.port()) + " message:" + mess;
        for (auto &user : _online_user)
        {
            if (user != peer)
                sendto(sockfd, mess.c_str(), mess.size(), 0, (struct sockaddr *)&(user.Netaddr()), sizeof(user.Netaddr()));
        }
        if (mess == "QUIT")
        {
            for (vector<Inetaddr>::iterator it = _online_user.begin(); it != _online_user.end(); it++)
            {
                if (*it == peer)
                {
                    _online_user.erase(it);
                    LOG(Loglevel::INFO) << "delete a user. IP:" << peer.ip() << " " << "port:" << peer.port();
                    return;
                }
            }
        }
    }
    ~Route()
    {
    }
};